package com.qinsoft.frame.utils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/** 
 * LocalHost类描述：获取本机ip
 */
public class LocalHost
{

    private static String ip = null;
    /**
     * getIp方法描述：得到当前用户ip
     * @param: 
     * @return:
     */
    public static String getIp()
    {
        if (ip != null) { return ip; }
        //初始化ip地址标记
        try
        {
            byte[] ips = InetAddress.getLocalHost().getAddress();
            StringBuffer sBuffer = new StringBuffer();
            sBuffer.append(ips[0] & 0xFF).append(".");
            sBuffer.append(ips[1] & 0xFF).append(".");
            sBuffer.append(ips[2] & 0xFF).append(".");
            sBuffer.append(ips[3] & 0xFF);
            return sBuffer.toString();
        }
        catch (UnknownHostException e)
        {
        }
        return null;
    }
    
    public static String getIp(HttpServletRequest request)
    {
        String clientIp = request.getHeader("x-forwarded-for");
        if ((clientIp == null) || (clientIp.length() == 0)
                || ("unknown".equalsIgnoreCase(clientIp))) {
            clientIp = request.getHeader("Proxy-Client-IP");
        }
        if ((clientIp == null) || (clientIp.length() == 0)
                || ("unknown".equalsIgnoreCase(clientIp))) {
            clientIp = request.getHeader("WL-Proxy-Client-IP");
        }
        if ((clientIp == null) || (clientIp.length() == 0)
                || ("unknown".equalsIgnoreCase(clientIp))) {
            clientIp = request.getRemoteAddr();
        }
        return clientIp;
    }
    
    /**
     * 根据名字获取cookie
     * @param request
     * @param name cookie名字
     * @return
     */
    public static Cookie getCookieByName(HttpServletRequest request,String name){
        Map<String,Cookie> cookieMap = ReadCookieMap(request);
        if(cookieMap.containsKey(name)){
            Cookie cookie = (Cookie)cookieMap.get(name);
            return cookie;
        }else{
            return null;
        }   
    }
     
     
     
    /**
     * 将cookie封装到Map里面
     * @param request
     * @return
     */
    private static Map<String,Cookie> ReadCookieMap(HttpServletRequest request){  
        Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
        Cookie[] cookies = request.getCookies();
        if(null!=cookies){
            for(Cookie cookie : cookies){
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }
}

